import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class jucDemo {
    public static void main(String[] args) {
        resource2 r2 = new resource2();
        new Thread(() -> { for (int i = 0; i < 10; i++) r2.showA(); }, "线程A").start();
        new Thread(() -> { for (int i = 0; i < 10; i++) r2.showB(); }, "线程B").start();
        new Thread(() -> { for (int i = 0; i < 10; i++) r2.showC(); }, "线程C").start();
        System.out.println("添加了一行输出");
    }
}
class resource2{
    private int number = 1;
    private int count = 0;
    private Lock lock = new ReentrantLock();
    //使用Lock对象，创建监视器
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void showA(){
        lock.lock();
        try {
            while(number != 1){
                //condition1进入等待
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>"+count++);
            number = 2;
            //唤醒condition2
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            lock.unlock();
        }
    }
    public void showB(){
        lock.lock();
        try {
            while(number != 2){
                //condition2进入等待
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>"+count++);
            number = 3;
            //唤醒condition3
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            lock.unlock();
        }
    }
    public void showC(){
        lock.lock();
        try {
            while(number != 3){
                //condition3进入等待
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>"+count++);
            number = 1;
            //唤醒condition1
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally{
            lock.unlock();
        }
    }

}
